<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <title>Counter</title>
</head>
<body>
<div id="root">
  结果：
  <div id="result"></div>
  输入框：<input id="num" type="number"/><br/>
  操作：
  <button id="btn-add" onclick="handleClick()">+</button>
  <button id="btn-sub" onclick="handleClick()">-</button>
  <button id="btn-multi" onclick="handleClick()">*</button>
  <button id="btn-div" onclick="handleClick()">/</button>
</div>
</body>
<script>
  // 应用状态对象
  var state = {
    counter: 0
  }

  /**
   * 更新state的counter属性
   *
   * @param state   state.counter
   * @param action  \{type, num}
   * @returns {number}  更新后的counter数字
   */
  function updateCounter(state = 0, action) {
    state = parseInt(state)
    let num = parseInt(action.num)
    switch (action.type) {
      case 'ADD':
        return state + num;
      case 'SUB':
        return state - num;
      case 'MULTI':
        return state * num;
      case 'DIV':
        if (num === 0) {
          alert("0不能作除数");
          return state;
        } else {
          return state / num;
        }
      default:
        return state;
    }
  }

  /**
   * 管理整个应用的state
   *
   * @param state
   * @param action
   * @returns {{counter: number}}
   */
  function reducer(state = {}, action) {
    return {
      counter: updateCounter(state.counter, action)
    }
  }

  function handleClick() {
    const num = document.getElementById("num").value || 0;
    const {id} = event.target;
    let type = id.substring(id.lastIndexOf('-') + 1).toUpperCase();
    // 创建Action
    let action = {type, num};
    console.log(action)

    // 传给reducer处理
    state = reducer(state, action);
    console.log(state)

    // 更新视图
    render(state);
  }

  function render(state = {}) {
    document.getElementById("result").innerText = state.counter;
  }

  window.onload = function () {
    render(state);
  }

</script>
</html>